<template>
  <el-dialog v-model="parentShow" title="自定义来源分享" width="40%" align-center @close="parentClose" @open="parentOpen">
    <div class="source-custom">
      <div class="custom-top" v-loading="listLoading" v-if="props.sourceCustomNum > 0">
        <div class="table-header">
          <span class="table-title">来源列表</span>
          <!-- <span><i class="iconfont">&#xe6d2;</i>下载全部二维码</span> -->
        </div>
        <el-table :data="sourceList" border style="width: 100%">
          <el-table-column prop="sourceName" label="来源名称" width="180" />
          <el-table-column label="链接">
            <template #default="scope">
              <div class="data-link">
                <span class="link-item">{{ scope.row.sourceLink }}</span>
                <span class="copy-btn" @click="copyLink(scope.row.sourceLink)">复制</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分享素材" width="110">
            <template #default="scope">
              <el-popover placement="top" :width="234" trigger="click">
                <template #reference>
                  <span class="cursor-pointer">下载二维码</span>
                </template>
                <qrcodeImg class="qrcode-img" :shareInfo="scope.row" ref="qrcodeImgRef"></qrcodeImg>
                <div class="switch-btn" v-if="true" style="display: flex; justify-content: space-between; margin-top: 20px; padding-top: 15px; border-top: 1px solid #aaaaaa">
                  <el-switch v-model="scope.row.showName" :active-value="true" :inactive-value="false" />
                  <el-button type="primary" @click="handleDownload">下载二维码</el-button>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="70" v-if="props.isAdd">
            <template #default="scope">
              <el-dropdown>
                <i class="iconfont">&#xe719;</i>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="setSource(scope.row)">编辑</el-dropdown-item>
                    <el-dropdown-item @click="deleteSource(scope.row.sourceId)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-bottom">
          <div class="add-source" @click="setSource" v-if="props.isAdd">
            <el-icon>
              <Plus />
            </el-icon>
            添加来源
          </div>
          <el-pagination v-model:current-page="params.currentPage" v-model:page-size="params.pageSize" layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange">
            <el-button type="primary" text>确认</el-button>
          </el-pagination>
        </div>
      </div>
      <div class="custom-nodata" v-else>
        <div class="nodata-title">暂无自定义来源和分享链接</div>
        <div class="nodata-tips">
          设置后可用于区分表单收集的数据来源，以方便追踪每个来源的数据情况
          <br />
          可按场景、人群、位置等维度添加自定义来源，获取各来源分享链接地址或二维码
        </div>
        <div class="nodata-add" v-if="props.isAdd"><el-button type="primary" @click="setSource">添加来源</el-button></div>
      </div>
      <div class="custom-bottom" v-if="props.isAdd">
        <div class="bottom-title">自定义来源设置</div>
        <div class="setting-option">
          <div class="option-left">
            <div class="option-label">仅支持自定义来源访问</div>
            <div class="option-tip">开启后，普通的分享链接和二维码将无法访问表单</div>
          </div>
          <el-switch
            class="option-right"
            v-model="publishSetting.onlyCustom"
            :before-change="() => beforeChange('onlyCustom')"
            :active-value="true"
            :inactive-value="false"
            :disabled="props.sourceCustomNum === 0"
          />
        </div>
        <div class="setting-option">
          <div class="option-left">
            <div class="option-label">
              填写页展示来源名称
              <el-popover placement="top" :width="400" trigger="hover">
                <template #reference>
                  <i class="iconfont">&#xe8c8;</i>
                </template>
                <div class="setting-popover-tip">
                  <div class="tip-text">来源名称会展示到标题下方，一般适用于需要填写者需要辅助确认来源后填写答卷的场景</div>
                  <div class="tip-form">
                    <div class="form-label">这是表单标题</div>
                    <div class="form-des">这是表单的描述文案</div>
                    <span class="form-source">来源AAA</span>
                  </div>
                </div>
              </el-popover>
            </div>
            <div class="option-tip">开启后，将在填写页标题下方展示来源名称</div>
          </div>
          <el-switch
            class="option-right"
            v-model="publishSetting.showSourceName"
            :before-change="() => beforeChange('showSourceName')"
            :active-value="true"
            :inactive-value="false"
            :disabled="props.sourceCustomNum === 0"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <el-dialog v-model="childShow" :title="setTitle" width="30%" align-center @close="childClose">
    <div class="set-option">
      <div class="option-label">来源名称</div>
      <el-input v-model="sourceInfo.sourceName" placeholder="请输入内容" clearable></el-input>
      <div class="option-tip">来源名称可按场景、人群、位置等命名。如：老师和学生、A群和B群、检测点1和检测点2</div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="childClose">取消</el-button>
        <el-button type="primary" @click="setConfirm" :disabled="sourceInfo.sourceName && sourceInfo.sourceName == ''">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, watch, defineProps, defineEmits, nextTick } from 'vue'
import { useStore } from 'vuex'
import { Plus } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getCustomSource, addCustomSource, updateCustomSource, deleteCustomSource, updatePublishSetting } from '@/api/formDesign'
import qrcodeImg from './qrcodeImg.vue'

const props = defineProps({
  sourceCustomShow: {
    type: Boolean
  },
  formId: {
    type: String
  },
  sourceCustomNum: {
    type: Number
  },
  formLabel: {
    type: String
  },
  isAdd: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits(['update:sourceCustomShow', 'update:sourceCustomNum'])
const store = useStore()
const publishSetting = ref(JSON.parse(JSON.stringify(store.getters.formDesignInfo.publishSetting)))
const parentShow = ref(false)
watch(
  props,
  newVal => {
    parentShow.value = newVal.sourceCustomShow
  },
  { deep: true }
)
//父级弹窗关闭
const parentClose = () => {
  emits('update:sourceCustomShow', false)
}
// 父级弹窗打开
const parentOpen = () => {
  emits('update:sourceCustomShow', true)
  getSourceList()
}
//二级弹窗关闭时，一级显示
const childShow = ref(false)
const childClose = () => {
  childShow.value = false
  parentShow.value = true
  sourceInfo.value = {}
  setTitle.value = '添加来源'
}
//获取数据
const sourceList = ref([])
const total = ref(0)
const params = reactive({
  formId: props.formId,
  currentPage: 1,
  pageSize: 4
})
const listLoading = ref(false)
const getSourceList = async () => {
  listLoading.value = true
  try {
    let res = await getCustomSource(params)
    if (res.code === 20000) {
      sourceList.value = res.data.list.map(item => {
        let link
        if (process.env.NODE_ENV === 'development') {
          link = location.protocol + '//' + location.hostname + ':8080/?formKey=' + item.sourceLink
        } else {
          link = location.origin + '/formFront?formKey=' + item.sourceLink
        }
        return {
          ...item, // 复制对象的原有属性
          title: props.formLabel,
          formLink: link,
          showName: false
        }
      })
      total.value = res.data.total
    }
    listLoading.value = false
  } catch {
    listLoading.value = false
  }
}
const handleCurrentChange = () => {
  getSourceList()
}
//没有自定义资源的时候需将自定义来源配置更新为默认配置
watch(total, (newVal, oldVal) => {
  emits('update:sourceCustomNum', newVal)
  if (oldVal > newVal && newVal === 0) {
    publishSetting.value.onlyCustom = false
    publishSetting.value.showSourceName = false
    let params = {
      paperId: props.formId,
      publishSetting: publishSetting.value
    }
    updatePublishSetting(params)
  }
})
//复制链接
const copyLink = link => {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard
      .writeText(link)
      .then(() => {
        ElMessage({
          message: '复制成功',
          type: 'success'
        })
      })
      .catch(error => {
        ElMessage({
          message: '复制失败，请再次尝试',
          type: 'error'
        })
        console.log('复制链接到剪贴板时出错:', error)
      })
  } else {
    // 创建text area
    let textArea = document.createElement('textarea')
    textArea.value = link
    // 使text area不在viewport，同时设置不可见
    textArea.style.position = 'absolute'
    textArea.style.opacity = 0
    textArea.style.left = '-999999px'
    textArea.style.top = '-999999px'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()
    return new Promise((res, rej) => {
      if (document.execCommand('copy')) {
        res()
        ElMessage({
          message: '复制成功',
          type: 'success'
        })
      } else {
        rej()
        ElMessage({
          message: '复制失败，请再次尝试',
          type: 'error'
        })
      }
      textArea.remove()
    })
  }
}
//下载二维码
const qrcodeImgRef = ref(null)
const handleDownload = () => {
  nextTick(() => {
    qrcodeImgRef.value.downloadQrcodeImg()
  })
}
//添加或编辑来源
const setTitle = ref('添加来源')
const sourceInfo = ref({})
const setSource = async row => {
  if (row.sourceId) {
    setTitle.value = '编辑来源'
    sourceInfo.value = JSON.parse(JSON.stringify(row))
  } else {
    sourceInfo.value.name = ''
  }
  parentShow.value = false
  childShow.value = true
}
//确认添加或修改
const setConfirm = async () => {
  if (sourceInfo.value.sourceId) {
    let res = await updateCustomSource(sourceInfo.value)
    if (res.code === 20000) {
      ElMessage({
        message: '修改成功',
        type: 'success'
      })
      childClose()
    } else {
      ElMessage({
        message: '修改失败',
        type: 'success'
      })
    }
  } else {
    let params = {
      paperId: props.formId,
      ...sourceInfo.value
    }
    let res = await addCustomSource(params)
    if (res.code === 20000) {
      ElMessage({
        message: '添加成功',
        type: 'success'
      })
      childClose()
    } else {
      ElMessage({
        message: '添加失败',
        type: 'error'
      })
    }
  }
}
//删除来源
const deleteSource = id => {
  ElMessageBox.confirm('删除后已分享的链接或二维码将不支持访问，已收集数据仍然会保存并支持相关筛选', '确认要删除该条来源吗？', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消'
  })
    .then(async () => {
      await deleteCustomSource({ id })
      getSourceList()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}
//仅支持自定义来源配置更新
const beforeChange = key => {
  return new Promise(resolve => {
    let params = {
      paperId: props.formId,
      publishSetting: { ...publishSetting.value, [key]: !publishSetting.value[key] }
    }
    updatePublishSetting(params)
      .then(res => {
        if (res.code === 20000) {
          ElMessage({
            type: 'success',
            message: '更新成功'
          })
          resolve(true)
        } else {
          ElMessage({
            type: 'error',
            message: '更新失败，请重新更改'
          })
          resolve(false)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error)
        resolve(false)
      })
  })
}
</script>

<style lang="scss" scoped>
.source-custom {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 450px;
  font-size: 14px;
  color: #444444;

  .custom-top {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .table-title {
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }

      i {
        margin-right: 5px;
      }
    }

    ::v-deep .el-table th.el-table__cell {
      background-color: #f2f2f2;
      color: #333333;
    }

    .data-link {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .link-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .copy-btn {
        display: none;
        width: 50px;
        height: 20px;
        line-height: 22px;
        border: 1px solid #e4e4e4;
        border-radius: 4px;
        background: $mainColor;
        text-align: center;
        color: #fff;
        cursor: pointer;
      }
    }

    .data-link:hover {
      .copy-btn {
        flex-shrink: 0;
        display: inline-block;
      }
    }
    .table-bottom {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
      padding-left: 10px;

      .add-source {
        color: $mainColor;
        cursor: pointer;
      }
    }
  }
  .custom-nodata {
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 60px 0 80px 0;
    .nodata-title {
      margin-bottom: 20px;
      text-align: center;
      font-size: 18px;
      font-weight: 600;
      color: #333333;
    }
    .nodata-tips {
      margin-bottom: 20px;
      line-height: 1.5;
      text-align: center;
      color: #aaaaaa;
    }
    .nodata-add {
      text-align: center;
    }
  }

  .custom-bottom {
    .bottom-title {
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: 600;
      color: #333333;
    }

    .setting-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      .option-left {
        i {
          margin-left: 4px;
          padding: 4px;
        }
        i:hover {
          background: #e2e2e3;
          border-radius: 4px;
          cursor: pointer;
        }
      }
      .option-tip {
        margin-top: 10px;
        color: #aaaaaa;
      }
    }
  }
}
.set-option {
  margin-bottom: 20px;
  .option-label {
    margin-bottom: 10px;
    color: #444444;
  }
  .option-tip {
    margin-top: 10px;
    color: #aaaaaa;
  }
  .form-links {
    display: flex;
    flex-wrap: nowrap;
    .link-copy {
      margin: 0 10px;
    }
    .link-open {
      flex-shrink: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 38px;
      height: 38px;
      border: 1px solid #e4e4e4;
      border-radius: 4px;

      i {
        font-size: 16px;
      }
    }

    .link-open:hover {
      background: #f0f1f1;
    }
  }
}
.setting-popover-tip {
  .tip-text {
    margin-bottom: 15px;
    color: #444444;
  }
  .tip-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    .form-label {
      margin-bottom: 10px;
      font-size: 18px;
      font-weight: 600;
      color: #333333;
    }
    .form-des {
      margin-bottom: 10px;
      color: #aaaaaa;
    }
    .form-source {
      padding: 5px 10px;
      background: #e7f4ff;
      border-radius: 4px;
    }
  }
}
.cursor-pointer {
  cursor: pointer;
}
</style>
